<?php

namespace app\common\model;

use basic\ModelBasic;

class RelRecomandRoutes extends ModelBasic
{
	use \traits\ModelTrait;

	/**
	 * 设置where条件
	 * @Author   FW
	 * @DateTime 2021-01-12
	 * @Email    123763712@qq.com
	 * @param    [type]           $where [description]
	 * @param    string           $alias [description]
	 * @param    [type]           $model [description]
	 */
	public static function setWhere($where,$alias='m',$model=null){
        $model = $model===null ? new self() : $model;

        $model->alias($alias);

        if ( isset($where['recomand_id']) && $where['recomand_id'] > 0 ) {
        	$model->where(sprintf('%s.recomand_id=%d',$alias,$where['recomand_id']));
        }

        if ( isset($where['route_name']) && $where['route_name'] != '' ) {
        	$routesIds = "SELECT id FROM `eb_routes` WHERE `route_name` LIKE '%".$where['route_name']."%'";

        	$model->where(sprintf('%s.route_id IN (%s)',$alias,$routesIds));
        }

        if ( isset($where['route_type']) && $where['route_type'] != '' ) {
            $model->where(sprintf('%s.route_id IN (SELECT id FROM `eb_routes` WHERE `route_type`=%d)',$alias,$where['route_type']));
        }

        if ( isset($where['order']) && $where['order'] != '' ) {
            $model->order(sprintf('%s.%s' , $alias, $where['order']));
        } else {
            $model->order(sprintf('%s.sort ASC',$alias));
        }

        return $model;
    }

     /**
     * 列表
     * @Author   FW
     * @DateTime 2020-09-24
     * @Email    123763712@qq.com
     * @param    [type]
     * @return   [type]
     */
    public static function getList($where){
        $count =  self::setWhere($where)->count();
        $data  = [];
        if ( $count == 0 ) {
            return compact('data','count');
        }

        $data= self::setWhere($where)
        ->field("m.recomand_id,m.route_id,m.sort,r.route_name,(case r.route_type when 1 then '长线' when 2 then '短线' else '未知' end) as route_type_text")
        ->join('__ROUTES__ r' , 'm.route_id = r.id')
        ->page($where['page'] ?? 1,$where['limit'] ?? 10)
        ->select();
        return compact('data','count');
    }

    /**
     *供前台调用的关联线路列表
     */  
    public static function routes($recomand_id , $page = 1 , $limit = 10)
    {
    	$routes = self::alias('m')->field("r.*,r.route_name as title")
    	->join('__ROUTES__ r' , 'm.route_id = r.id')
    	->where('m.recomand_id',$recomand_id)
    	->page($page , $limit)
    	->order('m.sort ASC')
    	->select();
    	if ( !empty($routes) ) {
        	$routes = $routes->toArray();
        	$routes = Routes::process_list($routes);
        }
        return $routes;
    }
}//Class End
